<template>
  <home-layout>
    <template #title-item>
      <a-button size="small" @click="$router.go(-1)">返回上一级</a-button>
    </template>

    <a-steps :current="current" class="w-9/10 lg:w-2/3 mx-auto" :items="steps"> </a-steps>

    <div class="flex-1 p-3 children:box-border">
      <router-view v-slot="{ Component }">
        <transition :name="route.meta.transition as string" mode="out-in">
          <KeepAlive :include="caches">
            <component
              :is="Component"
              @processing="onCurrentStepProcess(route.meta.step as number)"
              @done="onCurretStepDone(route.meta.step as number)"
            />
          </KeepAlive>
        </transition>
      </router-view>
    </div>
  </home-layout>
</template>

<script setup lang="ts" name="Home">
import HomeLayout from '@/layouts/HomeLayout.vue'
import { NAME_STARTUP } from '@/router/constants'

import { StepProps } from 'ant-design-vue'

const router = useRouter()
const route = useRoute()

const caches = ref(undefined) as Ref<undefined | string[]>

const current = ref(0)

const steps: (StepProps & { next: string })[] = reactive([
  {
    title: '获取项目路径',
    description: 'git/workspace 路径',
    next: 'tree' // 下一个子路由名称
  },
  {
    title: '获取/调整项目菜单项',
    description: '增、删、改名',
    next: 'done'
  },
  {
    title: '完成初始化',
    description: '翻译、创建文件夹',
    next: 'startup'
  }
])

const stopWatch = watch(
  route,
  ({ meta, name }) => {
    if (name === NAME_STARTUP) stopWatch()

    const { step } = meta
    if (typeof step === 'number') {
      current.value = step
      steps[step].status = 'process'
      if (step !== steps.length - 1) steps[step + 1].status = void 0
    }
  },
  { immediate: true }
)

const onCurrentStepProcess = (step: number) => {
  const currentStep = steps[step]
  currentStep.status = 'process'
}

const onCurretStepDone = (step: number) => {
  const currentStep = steps[step]
  currentStep.status = 'finish'

  if (step < steps.length - 1) {
    steps[step + 1].status = 'process'
  }

  router.push({ name: currentStep.next })
}

onDeactivated(() => {
  caches.value = []
})
</script>
